<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" plain size="mini" type="primary"
                   @click="handleAddAssets">添加资产
        </el-button>
      </el-col>
      <right-toolbar :search="false" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="assetsRecordList" border>
      <el-table-column align="center" label="资产名称" prop="assetsName"/>
      <el-table-column align="center" label="资产类型" prop="assetsType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cld_assets_type" :value="scope.row.assetsType"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="资产型号" prop="assetsModel"/>
      <el-table-column align="center" label="资产单位" prop="assetsUnit"/>
      <el-table-column align="center" label="资产ID" prop="assetsIdCard"/>
      <el-table-column align="center" label="负责人" prop="personName"/>
      <el-table-column align="center" label="组别" prop="groupName">
        <template slot-scope="scope">
          <dict-tag v-if="scope.row.groupName" :options="dict.type.cld_project_groups"
                    :value="parseInt(scope.row.groupName)"/>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleUnbinding(scope.row)">解绑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
                @pagination="getList"/>

    <el-dialog :close-on-click-modal="false" :visible.sync="open" append-to-body title="设置项目资产" width="800px">
      <el-form ref="form" :model="form" label-width="80px" size="mini">
        <el-row :gutter="20">
          <el-form-item :rules="{
            required: true, message: '负责人不能为空', trigger: 'blur'
          }" label="负责人" prop="staffId">
            <el-cascader-panel v-model="form.staffId" :options="projectGroupOptions"></el-cascader-panel>
          </el-form-item>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button :disabled="form.staffId.length < 2" icon="el-icon-plus" plain size="mini" type="primary"
                       @click="handleAddSelectAssets">选择资产
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-table v-loading="loading" :data="form.assetsRecords" border>
            <el-table-column align="center" label="资产ID" prop="assetsIdCard"/>
            <el-table-column align="center" label="资产名称" prop="assetsName"/>
            <el-table-column align="center" label="资产类型" prop="assetsType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.cld_assets_type" :value="scope.row.assetsType"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="资产型号" prop="assetsModel"/>
            <el-table-column align="center" label="资产单位" prop="assetsUnit"/>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleDeleteAssets(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择资产 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isAssetsOpen" append-to-body title="选择资产"
               width="60%">
      <selected-assets v-if="isAssetsOpen" :isMultiple="true" :notAssetsIds="notAssetsIds" :recordStatus="1"
                       @change="handleAssetsChange"></selected-assets>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAssetsSelected">确 定</el-button>
        <el-button @click="isAssetsOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改资产 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isAssetsUpdateOpen" append-to-body title="项目资产"
               width="40%">
      <el-form ref="formEdit" :model="form" label-width="80px" size="mini">
        <el-row :gutter="20">
          <el-form-item label="负责人" prop="staffId">
            <el-cascader-panel v-model="form.staffId" :options="projectGroupOptions"></el-cascader-panel>
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-descriptions :column="6" border direction="vertical">
              <el-descriptions-item label="设备ID">{{ form.assetsIdCard }}</el-descriptions-item>
              <el-descriptions-item label="资产名称">{{ form.assetsName }}</el-descriptions-item>
              <el-descriptions-item label="资产类型">
                <dict-tag :options="dict.type.cld_assets_type"
                          :value="form.assetsType"/>
              </el-descriptions-item>
              <el-descriptions-item label="资产型号">{{ form.assetsModel }}</el-descriptions-item>
              <el-descriptions-item label="资产单位">{{ form.assetsUnit }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateForm">确 定</el-button>
        <el-button @click="isAssetsUpdateOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addPlacementRecord, batchAddPlacementRecord, getRecord, listRecord, updateRecord} from "@/api/cld/record";
import {selectGroupStaffByProjectId} from '@/api/cld/publicCommon'
import selectedAssets from '../assets/selectedAssets.vue';

export default {
  components: {selectedAssets},
  name: "addWorkPlan",
  dicts: ['cld_assets_type', 'cld_project_groups'],
  comments: {
    selectedAssets
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 项目资产列表
      assetsRecordList: [],
      // 添加项目资产
      open: false,
      // 选择资产弹框
      isAssetsOpen: false,
      // 资产修改弹框
      isAssetsUpdateOpen: false,
      form: {
        staffId: [],
      },
      // 项目id
      projectId: null,
      projectGroupOptions: [],
      // 资产临时存放
      temporaryList: [],
      // 资产记录
      notAssetsIds: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isNewUpdate: 1,
        projectId: null
      },
      // 总条数
      total: 0,

    };
  },
  created() {
    const projectId = this.$route.params && this.$route.params.projectId;
    if (projectId) {
      this.projectId = projectId;
      this.queryParams.projectId = projectId;
      this.getList();
      this.handleGetGroupAndStaff();
    }
  },
  methods: {
    // 查询项目资产
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then(response => {
        this.loading = false;
        this.assetsRecordList = response.rows;
        this.total = response.total;
      })
    },
    // 查询小组及在岗人员
    handleGetGroupAndStaff() {
      selectGroupStaffByProjectId(this.projectId).then(res => {
        this.projectGroupOptions = res.data;
      })
    },
    // 取消按钮
    cancel() {
      this.$tab.closePage();
    },
    // 表单重置
    reset() {
      this.form = {
        assetsRecords: [],
        // 负责人选择
        staffId: [],
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAddAssets() {
      this.reset();
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getRecord(row.assetsRecordId).then(response => {
        this.form = response.data;
        if (this.form.groupName && this.form.personId) {
          this.form.staffId = [parseInt(this.form.groupName), this.form.personId];
        } else {
          this.form.staffId = []
        }
        this.isAssetsUpdateOpen = true;
      });
    },
    // 修改提交
    submitUpdateForm() {
      this.$refs["formEdit"].validate(valid => {
        if (valid) {
          if (this.form.staffId.length < 2) {
            this.$message.error('请选择资产负责人！');
            return;
          }
          this.form.personId = this.form.staffId[1]
          updateRecord(this.form).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.isAssetsUpdateOpen = false;
            this.getList();
          });
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.assetsRecords.length == 0) {
            this.$message.error('请选择资产信息！');
            return;
          }
          batchAddPlacementRecord(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      })
    },
    // 解绑资产
    handleUnbinding(row) {
      this.$modal.confirm('是否确认解绑该资产？').then(function () {
        let form = {
          assetsRecordId: row.assetsRecordId,
          recordStatus: 1
        }
        return addPlacementRecord(form);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      });
    },
    // 选择资产
    handleAddSelectAssets() {
      this.notAssetsIds = this.form.assetsRecords.map(item => item.assetsRecordId);
      this.isAssetsOpen = true;
    },
    // 资产勾选监听
    handleAssetsChange(e) {
      this.temporaryList = e;
    },
    // 资产确认选择
    handleAssetsSelected() {
      this.temporaryList.forEach(i => {
        this.form.assetsRecords.push({
          ...i,
          projectId: this.projectId,
          personId: this.form.staffId[1],
          recordStatus: 2
        })
      })
      console.log(this.form.assetsRecords)
      this.isAssetsOpen = false;
    },
    /** 删除资产 */
    handleDeleteAssets(row) {
      const index = this.form.assetsRecords.indexOf(row);
      if (index > -1) {
        this.form.assetsRecords.splice(index, 1);
      }
      this.notAssetsIds = this.notAssetsIds.filter(function (item) {
        return item !== row.assetsRecordId;
      });
    },
  },
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
